import os
import re

def format_comments(content):
    # 处理单行注释 //
    content = re.sub(r'(?<!:)(//)(\s*)(?=\S)', r'// ', content)
    
    # 处理多行注释块
    def format_multiline(match):
        block = match.group()
        # 处理开头/*后的空格
        block = re.sub(r'(\/\*)(\s*)(?=\S)', r'/* ', block, count=1)
        # 处理结尾*/前的空格
        block = re.sub(r'(\s*)(\*\/)', r' */', block, count=1)
        
        lines = block.split('\n')
        formatted = []
        for i, line in enumerate(lines):
            if i == 0 or i == len(lines)-1:
                formatted.append(line)
                continue
            
            # 仅保留去左侧空白，移除星号后加空格的逻辑
            line = line.lstrip()
            formatted.append(line)
        
        return '\n'.join(formatted)
    
    # 使用非贪婪模式匹配多行注释（避免匹配字符串中的/* */）
    content = re.sub(r'/\*.*?\*/', format_multiline, content, flags=re.DOTALL)
    return content

def process_file(file_path):
    try:
        with open(file_path, 'r+', encoding='utf-8') as f:
            content = f.read()
            new_content = format_comments(content)
            if new_content != content:
                f.seek(0)
                f.write(new_content)
                f.truncate()
                print(f"Formatted: {file_path}")
    except Exception as e:
        print(f"Error processing {file_path}: {str(e)}")

def main(directory):
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(('.c', '.h')):
                process_file(os.path.join(root, file))

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2:
        print("Usage: python comment_formatter.py <target_directory>")
        sys.exit(1)
    main(sys.argv[1])